package com.chance.cc.crawler.development.command.job.domain.xhs.daily;

import com.alibaba.fastjson.JSON;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerJob;
import com.chance.cc.crawler.core.downloader.HttpConstant;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequestBody;
import com.chance.cc.crawler.core.downloader.proxy.Proxy;
import com.chance.cc.crawler.core.filter.FilterInfo;
import com.chance.cc.crawler.core.filter.FilterUtils;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.development.command.job.CrawlerJobCommand;
import com.chance.cc.crawler.meta.core.bean.CrawlerMetaConstant;
import com.chance.cc.crawler.meta.core.bean.job.CrawlerScheduleJob;
import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.List;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerRequestType.*;
import static com.chance.cc.crawler.development.command.publish.douyin.DYPublishCrawlerJob.metaServerIP;
import static com.chance.cc.crawler.development.command.publish.douyin.DYPublishCrawlerJob.metaServerPort;

/**
 * @author bx
 * @date 2020/12/6 0006 12:44
 */
public class XHSTraceCommentCrawlerScheduleJob {

    public static String domainId = "xhs";
    public static String site = "xhs-comment";
    public static final String commentStartUrl = "https://start/fe_api/burdock/weixin/v2/notes/start/comments/start";
    private static CrawlerJobCommand crawlerJobCommand = new CrawlerJobCommand(metaServerIP,metaServerPort);
        private static final String metaServer = "http://192.168.1.215:9599";
//    private static final String metaServer = "http://localhost:9599";

    private static Proxy proxy = new Proxy();

    static {
        //代理配置
        proxy.setHost("http-dyn.abuyun.com");
        proxy.setPort(9020);
        proxy.setUsername("HL89Q19E86E2987D");
        proxy.setPassword("71F33D94CE5F7BF2");
    }

    public static void main(String[] args) {

//        publishSearchCrawlerScheduleJobInfo();
        System.out.println(crawlerSchduler().generateCrawlerTriggerKey());
    }

    public static CrawlerJob publishSearchCrawlerScheduleJobInfo(){


        CrawlerJob crawlerSchduler =  crawlerSchduler();

        //发布定时采集作业
        CrawlerScheduleJob crawlerScheduleJob = new CrawlerScheduleJob();
        crawlerScheduleJob.setDomain(domainId);
        crawlerScheduleJob.setCrawlerJob(JSON.toJSONString(crawlerSchduler));
        crawlerScheduleJob.setJobType(CrawlerMetaConstant.ScheduleCrawlerJobType.crawler.enumVal());
        crawlerScheduleJob.setNote("小红书评论定时采集");
        crawlerScheduleJob.setCrawlerKey(crawlerSchduler.generateCrawlerKey());
        HttpPage page = crawlerJobCommand.addOrUpdateCrawlerScheduleJob(crawlerScheduleJob);
        System.out.println("发布crawler作业：" + page.getRawText());
        return crawlerSchduler;

    }

    /**
     * xhs评论追溯job 不会进入任何脚本。
     * 该job的用途，是为了可以定时调用meta service中初始7天内主贴评论的api
     * url:http://192.168.1.215:9599/crawler/domain/xhs/api/v1/results/queue/init
     * 此处把该请求封装成supportSourceRecord，由调度统一启动任务（每天一次），初始7天内主贴评论
     * 初始的评论record 会统一放入 实时评论采集队列，由实时评论采集任务统一处理
     * @return
     */
    public static CrawlerJob crawlerSchduler() {

        CrawlerEnum.CrawlerRecordFilter filter = CrawlerEnum.CrawlerRecordFilter.keyOrDateRange;
        List<FilterInfo> filterInfos = Arrays.asList(FilterUtils.redisFilterKeyInfo(StringUtils.joinWith("-","filter",domainId,site,"queue"))
                ,FilterUtils.dateRangeFilterInfo(24*7,null));

        CrawlerRequestRecord crawlerCommentRequestRecord = CrawlerRequestRecord.builder()
                .startPageRequest(domainId,turnPage)
                .httpUrl("") //置空，保证不会进入任何脚本
                .releaseTime(System.currentTimeMillis())
                .build();
        crawlerCommentRequestRecord.getHttpConfig().setResponseTextGenerateHtml(false);
        String requestQueueName = StringUtils.joinWith("-","crawler",domainId,site,"queue");
        String articleAccumQueueName = StringUtils.joinWith("-",  domainId,"article","accumulate", "queue");
        String url = metaServer + "/crawler/domain/xhs/api/v1/results/queue/init?requestQueueName=%s&articleAccumQueueName=%s&hourFromNow=%d";

        //初始7天内评论record
        CrawlerRequestRecord requestRecord = CrawlerRequestRecord.builder()
                .startPageRequest(domainId,turnPage)
                .httpUrl(commentStartUrl)
                .releaseTime(System.currentTimeMillis())
                .needWashed(true)
                .proxy(proxy)
                .build();
        requestRecord.setFilter(filter);
        requestRecord.setFilterInfos(filterInfos);

        requestRecord.tagsCreator().bizTags().addDomain(domainId);
        requestRecord.tagsCreator().bizTags().addSite(site);

        CrawlerRequestRecord initCommentCrawlerRecord = CrawlerRequestRecord.builder()
                .startPageRequest("xhs_comment_trace",turnPageItem)
                .httpUrl(String.format(url,requestQueueName,articleAccumQueueName,24*7))
                .requestLabelTag(supportSource)
                .requestLabelTag(internalDownload)
                .build();
        HttpRequestBody jsonBody = HttpRequestBody.json(JSON.toJSONString(requestRecord), "utf-8");
        initCommentCrawlerRecord.getHttpRequest().setMethod(HttpConstant.Method.POST);
        initCommentCrawlerRecord.getHttpRequest().setRequestBody(jsonBody);

        return CrawlerJob.builder()
                .triggerInfo(
                        domainId,
                        CrawlerMetaConstant.ScheduleJobTrigger_Cron,
                        System.currentTimeMillis(),
                        StringUtils.joinWith("-", domainId, site, "trace",CrawlerMetaConstant.ScheduleJobTriggerJob_Realtime))
                .crawlerRequestQueue(CrawlerMetaConstant.redisRequestQueue(requestQueueName))
                .kafkaResultPipeline("article_comment","tmp_social_media",null)
                .requestRecord(crawlerCommentRequestRecord)
                .supportRecord(initCommentCrawlerRecord)
                .build();
    }
}
